<template>
    <div class="traceability-container">
        <!-- 顶部操作栏 -->
        <div class="toolbar">
            <el-button type="primary" @click="onOpen()">新增</el-button>
            <el-button type="danger" :disabled="!hasSelection" @click="onDelete">删除</el-button>
            <div style="float: right;">
                <el-button @click="onRefresh" circle title="刷新"><el-icon>
                        <Refresh />
                    </el-icon></el-button>
                <el-button @click="showColumnConfig = true" circle title="配置"><el-icon>
                        <Setting />
                    </el-icon></el-button>
                <el-button @click="toggleMoreQuery" circle title="更多查询"><el-icon>
                        <Filter />
                    </el-icon></el-button>
            </div>
        </div>
        <!-- 更多查询栏 -->
        <el-drawer v-model="showMoreQuery" title="更多查询" direction="ttb" size="auto">
            <el-form :inline="true" :model="searchForm" class="more-query-form">
                <el-form-item label="商品名称">
                    <el-input v-model="searchForm.GoodsName" placeholder="商品名称" />
                </el-form-item>
                <el-form-item label="生产批次">
                    <el-input v-model="searchForm.ProductionBatch" placeholder="生产批次" />
                </el-form-item>
                <el-form-item label="保质期(天)">
                    <el-input v-model="searchForm.ShelfLifeDays" placeholder="保质期" />
                </el-form-item>
                <el-form-item label="生产许可证号">
                    <el-input v-model="searchForm.ProductionLicenseNumber" placeholder="生产许可证号" />
                </el-form-item>
                <el-form-item label="生产企业">
                    <el-input v-model="searchForm.ManufacturingEnterprise" placeholder="生产企业" />
                </el-form-item>
                <el-form-item label="创建人">
                    <el-input v-model="searchForm.Creator" placeholder="创建人" />
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-date-picker v-model="searchForm.CreateTime" type="date" placeholder="选择日期" />
                </el-form-item>
                <el-form-item label="修改人">
                    <el-input v-model="searchForm.Updator" placeholder="修改人" />
                </el-form-item>
                <el-form-item label="修改时间">
                    <el-date-picker v-model="searchForm.UpdateTime" type="date" placeholder="选择日期" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSearch()">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
        <!-- 列配置弹窗 -->
        <el-dialog v-model="showColumnConfig" title="列显示/隐藏配置" width="400px">
            <el-checkbox-group v-model="visibleColumns">
                <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">{{ col.label }}</el-checkbox>
            </el-checkbox-group>
            <template #footer>
                <el-button @click="showColumnConfig = false">关闭</el-button>
            </template>
        </el-dialog>
        <!-- 数据表格 -->
        <el-table :data="tableData" border style="width:100%; margin-top: 10px;" @selection-change="onSelectionChange"
            ref="tableRef">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="goodsName" label="商品名称" width="120" v-if="visibleColumns.includes('goodsName')" />
            <el-table-column prop="productionBatch" label="生产批次" width="180"
                v-if="visibleColumns.includes('productionBatch')" />
            <el-table-column prop="shelfLifeDays" label="保质期（天）" width="180"
                v-if="visibleColumns.includes('shelfLifeDays')" />
            <el-table-column prop="productionLicenseNumber" label="生产许可证号" width="180"
                v-if="visibleColumns.includes('productionLicenseNumber')" />
            <el-table-column prop="manufacturingEnterprise" label="生产企业" width="180"
                v-if="visibleColumns.includes('manufacturingEnterprise')" />
            <el-table-column prop="infoCompleteness" label="信息完整度" width="180"
                v-if="visibleColumns.includes('infoCompleteness')" />
            <el-table-column prop="coverImage" label="封面图" width="180" v-if="visibleColumns.includes('coverImage')">
                <template v-slot="hh">
                    <img :src="hh.row.coverImage" class="avatar" />
                </template>
            </el-table-column>
            <el-table-column prop="creator" label="创建人" width="180" v-if="visibleColumns.includes('creator')" />
            <el-table-column prop="createTime" label="创建时间" width="180" v-if="visibleColumns.includes('createTime')">
                <template v-slot="hh">
                    {{ moment(hh.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
                </template>
            </el-table-column>
            <el-table-column prop="updator" label="修改人" width="180" v-if="visibleColumns.includes('updator')">
                <template v-slot="hh">
                    <span v-if="hh.row.updator == null">暂无数据</span>
                    <span v-else>{{ hh.row.updator }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="修改时间" width="180" v-if="visibleColumns.includes('updateTime')">
                <template v-slot="hh">
                    <span v-if="hh.row.updateTime == null">暂无数据</span>
                    <span v-else>{{ moment(hh.row.updateTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="260">
                <template v-slot="hh">
                    <el-button type="primary" link @click="onDetail(hh.row)">详情</el-button>
                    <el-button type="primary" link @click="onEdit(hh.row)">修改</el-button>
                    <el-button type="primary" link @click="handleExport(hh.row)">导出溯源码</el-button>
                    <el-button type="danger" link @click="onDeleteSingle(hh.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination style="margin-top: 16px; text-align: right;" background
            layout="prev, pager, next, jumper, ->, total" :total="totalCount" :page-size="pageSize"
            :current-page.sync="currentPage" @current-change="onPageChange" />
        <!-- 新增弹窗 -->
        <el-dialog title="新增溯源商品" v-model="addDialogVisible" width="500px">
            <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="120px">
                <el-form-item label="商品名称" prop="productName" required>
                    <el-select v-model="addForm.productName" placeholder="请选择商品名称" size="large" style="width: 240px">
                        <el-option v-for="item in bindname" :label="item.goodsname" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="生产批次" prop="productionBatch" required>
                    <el-input v-model="addForm.productionBatch" maxlength="30" />
                </el-form-item>
                <el-form-item label="保质期（天）" prop="shelfLifeDays" required>
                    <el-input v-model.number="addForm.shelfLifeDays" />
                </el-form-item>
                <el-form-item label="生产许可证号" prop="productionLicenseNumber" required>
                    <el-input v-model="addForm.productionLicenseNumber" maxlength="30" />
                </el-form-item>
                <el-form-item label="生产企业" prop="manufacturingEnterprise" required>
                    <el-input v-model="addForm.manufacturingEnterprise" maxlength="30" />
                </el-form-item>
                <el-form-item label="封面图" prop="coverImage" required>
                    <el-upload class="avatar-uploader" action="http://10.222.11.20:5174/api/Img/Upload"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="addForm.coverImage" :src="addForm.coverImage" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onAddSubmit()">保存</el-button>
            </div>
        </el-dialog>

        <!-- 修改弹窗 -->
        <el-dialog title="修改溯源商品" v-model="editDialogVisible" width="500px">
            <el-form :model="editForm" :rules="addRules" ref="editFormRef" label-width="120px">
                <el-form-item label="商品名称" prop="productName" required>
                    <el-select v-model="editForm.productName" placeholder="请选择商品名称" size="large" style="width: 240px">
                        <el-option v-for="item in bindname" :label="item.goodsname" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="生产批次" prop="productionBatch" required>
                    <el-input v-model="editForm.productionBatch" maxlength="30" />
                </el-form-item>
                <el-form-item label="保质期（天）" prop="shelfLifeDays" required>
                    <el-input v-model.number="editForm.shelfLifeDays" />
                </el-form-item>
                <el-form-item label="生产许可证号" prop="productionLicenseNumber" required>
                    <el-input v-model="editForm.productionLicenseNumber" maxlength="30" />
                </el-form-item>
                <el-form-item label="生产企业" prop="manufacturingEnterprise" required>
                    <el-input v-model="editForm.manufacturingEnterprise" maxlength="30" />
                </el-form-item>
                <el-form-item label="封面图" prop="coverImage" required>
                    <el-upload class="avatar-uploader" action="http://10.222.11.20:5174/api/Img/Upload"
                        :show-file-list="false" :on-success="handleEditAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="editForm.coverImage" :src="editForm.coverImage" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onEditSubmit()">保存</el-button>
            </div>
        </el-dialog>
        <!-- 导出溯源码弹窗 -->
        <el-dialog v-model="exportDialogVisible" title="导出溯源码" width="400px">
            <el-form :model="exportForm" :rules="exportRules" ref="exportFormRef" label-width="100px">
                <el-form-item label="导出数量" prop="count">
                    <el-input v-model="exportForm.count" maxlength="4" placeholder="请输入1-9999的数字" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="exportDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleExport">导出</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { axiostraceabliityr } from '@/http/axiosRead';
import { axiostraceabliityw } from '@/http/axiosWrtie';
import { ElMessage, ElMessageBox } from 'element-plus';

const tableData = ref([]);
const totalCount = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const hasSelection = ref(false);
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const bindname = ref()
const bind = () => {
    axiostraceabliityr.get('/api/Traceability/GetGoodsAll').then((res: any) => {
        bindname.value = res.data.data
    })
}
const addForm = ref({
    productName: '',
    productionBatch: '',
    shelfLifeDays: '',
    productionLicenseNumber: '',
    manufacturingEnterprise: '',
    infoCompleteness: '0%',
    coverImage: '',
    creator: localStorage.getItem("name"),
    createTime: null,
    updator: null,
    updateTime: null
});

const editForm = ref({
    id: 0,
    productName: '',
    productionBatch: '',
    shelfLifeDays: '',
    productionLicenseNumber: '',
    manufacturingEnterprise: '',
    coverImage: '',
    updator: localStorage.getItem("name")
});
const addRules = {
    productName: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
    ],
    productionBatch: [
        { required: true, message: '请输入生产批次', trigger: 'blur' },
        { max: 30, message: '最多输入30个字符', trigger: 'blur' }
    ],
    shelfLifeDays: [
        { required: true, message: '请输入保质期', trigger: 'blur' },
        { type: 'number', message: '只能输入数字', trigger: 'blur' },
    ],
    productionLicenseNumber: [
        { required: true, message: '请输入生产许可证号', trigger: 'blur' },
        { max: 30, message: '最多输入30个字符', trigger: 'blur' }
    ],
    manufacturingEnterprise: [
        { required: true, message: '请输入生产企业', trigger: 'blur' },
        { max: 30, message: '最多输入30个字符', trigger: 'blur' }
    ],
    coverImage: [
        { required: true, message: '请上传封面图', trigger: 'change' }
    ]
};
const addFormRef = ref();
const tableRef = ref();

const showMoreQuery = ref(false);
const showColumnConfig = ref(false);
const allColumns = [
    { prop: 'goodsName', label: '商品名称' },
    { prop: 'productionBatch', label: '生产批次' },
    { prop: 'shelfLifeDays', label: '保质期（天）' },
    { prop: 'productionLicenseNumber', label: '生产许可证号' },
    { prop: 'manufacturingEnterprise', label: '生产企业' },
    { prop: 'infoCompleteness', label: '信息完整度' },
    { prop: 'coverImage', label: '封面图' },
    { prop: 'creator', label: '创建人' },
    { prop: 'createTime', label: '创建时间' },
    { prop: 'updator', label: '修改人' },
    { prop: 'updateTime', label: '修改时间' }
];
const visibleColumns = ref(allColumns.map(col => col.prop));
const toggleMoreQuery = () => { showMoreQuery.value = !showMoreQuery.value; };
const searchForm = ref({
    GoodsName: '',
    ProductionBatch: '',
    ShelfLifeDays: '',
    ProductionLicenseNumber: '',
    ManufacturingEnterprise: '',
    Creator: '',
    CreateTime: '',
    Updator: '',
    UpdateTime: ''
});
const resetSearch = () => {
    searchForm.value = {
        GoodsName: '',
        ProductionBatch: '',
        ShelfLifeDays: '',
        ProductionLicenseNumber: '',
        ManufacturingEnterprise: '',
        Creator: '',
        CreateTime: '',
        Updator: '',
        UpdateTime: ''
    };
};

// 查询接口
const fetchTableData = () => {
    // 时间字段转北京时间字符串
    let createTimeStr = searchForm.value.CreateTime
        ? moment(searchForm.value.CreateTime).utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
        : '';
    let updateTimeStr = searchForm.value.UpdateTime
        ? moment(searchForm.value.UpdateTime).utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
        : '';
    const params = {
        Index: currentPage.value,
        Size: pageSize.value,
        GoodsName: searchForm.value.GoodsName,
        ProductionBatch: searchForm.value.ProductionBatch,
        ShelfLifeDays: searchForm.value.ShelfLifeDays,
        ProductionLicenseNumber: searchForm.value.ProductionLicenseNumber,
        ManufacturingEnterprise: searchForm.value.ManufacturingEnterprise,
        Creator: searchForm.value.Creator,
        CreateTime: createTimeStr,
        Updator: searchForm.value.Updator,
        UpdateTime: updateTimeStr
    };
    axiostraceabliityr.get('/api/Traceability/GetGoodsTraceabilityPage', { params }).then((res: any) => {
        tableData.value = res.data.pageData;
        totalCount.value = res.data.totaCount;
    });
};

// 新增接口
const onAddSubmit = () => {
    (addFormRef.value as any).validate(async (valid: boolean) => {
        if (!valid) return;
        const params = {
            productName: addForm.value.productName,
            productionBatch: addForm.value.productionBatch,
            shelfLifeDays: addForm.value.shelfLifeDays,
            productionLicenseNumber: addForm.value.productionLicenseNumber,
            manufacturingEnterprise: addForm.value.manufacturingEnterprise,
            infoCompleteness: addForm.value.infoCompleteness, // 可根据实际需求补充
            coverImage: addForm.value.coverImage,
            creator: addForm.value.creator,
            createTime: addForm.value.createTime,
            updator: addForm.value.updator,
            updateTime: addForm.value.updateTime
        };
        const res = await axiostraceabliityw.post('/api/Traceability/AddProductTraceability', params);
        if (res.data && res.data.code === 200) {
            ElMessage.success(res.data.msg)
            addDialogVisible.value = false;
            (addFormRef.value as any).resetFields();
            fetchTableData();
        }
        else {
            ElMessage.error(res.data.msg)
            addDialogVisible.value = false;
            (addFormRef.value as any).resetFields();
            fetchTableData();
        }
    });
};
import { useRouter } from 'vue-router'
const router = useRouter();
// 事件方法
// 详情按钮点击事件
const onDetail = (row: any) => {
    router.push({
        path: 'TraceabilityDetail',
        query: {
            id: row.id
        }
    })
};

// 修改按钮点击事件
const onEdit = (row: any) => {
    editForm.value = {
        id: row.id,
        productName: row.goodsId,
        productionBatch: row.productionBatch,
        shelfLifeDays: row.shelfLifeDays,
        productionLicenseNumber: row.productionLicenseNumber,
        manufacturingEnterprise: row.manufacturingEnterprise,
        coverImage: row.coverImage,
        updator: localStorage.getItem("name")
    };
    editDialogVisible.value = true;
};

// 导出溯源码按钮点击事件
const exportDialogVisible = ref(false);
const exportForm = ref({ count: '' });
const exportFormRef = ref();
const exportRules = {
    count: [
        { required: true, message: '请输入导出数量', trigger: 'blur' },
        { pattern: /^[1-9]\d{0,3}$/, message: '请输入1-9999之间的数字', trigger: 'blur' }
    ]
};

const handleExport = async (row: any) => {
    try {
        // 这里可以根据需要传递row.id等参数
        const res =await axiostraceabliityw.post(
            '/api/Traceability/ExportCodes',
            { Id: row.id },
            { responseType: 'blob' }
        );
        const blob = new Blob([res.data], { type: 'application/zip' });
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '溯源码二维码.zip';
        link.click();
        window.URL.revokeObjectURL(link.href);
        ElMessage.success('导出成功');
        exportDialogVisible.value = false;
    } catch (e) {
        ElMessage.error('导出失败');
    }
}

// 单个删除按钮点击事件
const onDeleteSingle = async (row: any) => {
    try {
        await ElMessageBox.confirm('确定要删除该记录吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        const res = await axiostraceabliityw.post('/api/Traceability/DeleteProductTraceabilityBatch', { ids: [row.id] });

        if (res.data && res.data.code === 200) {
            ElMessage.success(res.data.msg);
            fetchTableData();
        } else {
            ElMessage.error(res.data.msg || '删除失败');
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败');
            console.error('删除失败:', error);
        }
    }
};

// 批量删除按钮点击事件
const onDelete = async () => {
    const selectedRows = tableRef.value.getSelectionRows();
    if (!selectedRows || selectedRows.length === 0) {
        ElMessage.warning('请选择要删除的记录');
        return;
    }

    try {
        await ElMessageBox.confirm('确定要删除选中的记录吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        const ids = selectedRows.map((row: any) => row.id);
        const res = await axiostraceabliityw.post('/api/Traceability/DeleteProductTraceabilityBatch', { ids });

        if (res.data && res.data.code === 200) {
            ElMessage.success(res.data.msg);
            fetchTableData();
        } else {
            ElMessage.error(res.data.msg || '删除失败');
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败');
            console.error('删除失败:', error);
        }
    }
};

const onSearch = () => { currentPage.value = 1; fetchTableData(); };
const onPageChange = (page: number) => { currentPage.value = page; fetchTableData(); };
const onSelectionChange = (selection: any[]) => { hasSelection.value = selection.length > 0; };
const onOpen = () => { addDialogVisible.value = true };

// 工具栏按钮事件
const onRefresh = () => { fetchTableData(); };
const onConfig = () => { ElMessage.info('配置功能开发中'); };
const onMoreQuery = () => { ElMessage.info('更多查询功能开发中'); };

onMounted(() => {
    bind();
    fetchTableData();
});

import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import moment from 'moment';

const handleAvatarSuccess = (val: any) => {
    addForm.value.coverImage = val;
}

const handleEditAvatarSuccess = (val: any) => {
    editForm.value.coverImage = val;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png') {
        return true
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('大小不能超过 2MB!')
        return false
    }
    else {
        ElMessage.error('必须是jpg或png')
        return false
    }
}

const editFormRef = ref();

const onEditSubmit = () => {
    (editFormRef.value as any).validate(async (valid: boolean) => {
        if (!valid) return;

        try {
            const res = await axiostraceabliityw.post('/api/Traceability/UpdateProductTraceability', editForm.value);

            if (res.data && res.data.code === 200) {
                ElMessage.success(res.data.msg);
                editDialogVisible.value = false;
                (editFormRef.value as any).resetFields();
                fetchTableData();
            } else {
                ElMessage.error(res.data.msg || '修改失败');
            }
        } catch (error) {
            ElMessage.error('修改失败');
            console.error('修改失败:', error);
        }
    });
}
</script>

<style scoped>
.traceability-container {
    padding: 24px;
}

.toolbar {
    margin-bottom: 12px;
}

.search-bar {
    margin-bottom: 12px;
}

.avatar-uploader {
    display: inline-block;
}

.avatar-uploader-icon {
    font-size: 32px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
}

.avatar {
    width: 80px;
    height: 80px;
    display: block;
}
</style>